package com.sqlcheck.controller;

import com.sqlcheck.common.Result;
import com.sqlcheck.dto.request.TestDatabaseConnectionRequest;
import com.sqlcheck.dto.response.TestDatabaseConnectionResponse;
import com.sqlcheck.service.DatabaseConnectionTestService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/database")
@RequiredArgsConstructor
@Tag(name = "数据库管理", description = "数据库连接测试和管理相关接口")
public class DatabaseController {

    private final DatabaseConnectionTestService connectionTestService;

    @PostMapping("/test-connection")
    @Operation(summary = "测试数据库连接", description = "测试指定的数据库连接参数是否有效")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "测试完成", 
                content = @Content(schema = @Schema(implementation = TestDatabaseConnectionResponse.class))),
            @ApiResponse(responseCode = "400", description = "请求参数无效")
    })
    public Result<TestDatabaseConnectionResponse> testConnection(
            @Valid @RequestBody @io.swagger.v3.oas.annotations.parameters.RequestBody(
                description = "数据库连接测试请求", required = true,
                content = @Content(schema = @Schema(implementation = TestDatabaseConnectionRequest.class))
            ) TestDatabaseConnectionRequest request) {

        log.info("收到数据库连接测试请求: {}:{}@{}", request.getUsername(), request.getHost(), request.getDatabase());
        
        TestDatabaseConnectionResponse response = connectionTestService.testConnection(request);
        
        if (response.isSuccess()) {
            return Result.success(response);
        } else {
            return Result.error(response.getMessage());
        }
    }

    @GetMapping("/versions")
    @Operation(summary = "获取数据库版本选项", description = "根据数据库类型获取对应的版本选项列表")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "获取成功"),
            @ApiResponse(responseCode = "400", description = "参数无效")
    })
    public Result<Map<String, List<String>>> getDatabaseVersions(
            @RequestParam(required = false) 
            @Schema(description = "数据库类型，如果不指定则返回所有类型的版本", example = "MYSQL")
            String dbType) {
        
        log.info("获取数据库版本选项，类型: {}", dbType);
        
        Map<String, List<String>> versions = new HashMap<>();
        
        if (dbType == null || dbType.trim().isEmpty()) {
            // 返回所有数据库类型的版本
            versions.put("MYSQL", getMySQLVersions());
            versions.put("ORACLE", getOracleVersions());
        } else {
            String upperDbType = dbType.trim().toUpperCase();
            switch (upperDbType) {
                case "MYSQL":
                    versions.put("MYSQL", getMySQLVersions());
                    break;
                case "ORACLE":
                    versions.put("ORACLE", getOracleVersions());
                    break;
                default:
                    return Result.error("不支持的数据库类型: " + dbType);
            }
        }
        
        return Result.success(versions);
    }

    /**
     * 获取MySQL版本列表
     */
    private List<String> getMySQLVersions() {
        return List.of(
            "5.7.44",
            "8.0.28", 
            "8.0.32",
            "8.0.35",
            "8.0.36",
            "8.0.37",
            "8.0.38",
            "8.0.39"
        );
    }

    /**
     * 获取Oracle版本列表
     */
    private List<String> getOracleVersions() {
        return List.of(
            "11g Release 2 (11.2.0.4)",
            "12c Release 1 (12.1.0.2)", 
            "12c Release 2 (12.2.0.1)",
            "18c (18.3.0)",
            "19c (19.3.0)",
            "19c (19.8.0)",
            "19c (19.11.0)",
            "21c (21.3.0)"
        );
    }
}